import React, { useState, useEffect } from 'react';
import { Menu, X, Package, Database, Plus, RefreshCw, Trash2, AlertTriangle, CheckCircle, XCircle } from 'lucide-react';
import { Button } from './components/ui/button';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from './components/ui/dialog';
import { Input } from './components/ui/input';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from './components/ui/table';
import { Progress } from './components/ui/progress';
import { Checkbox } from './components/ui/checkbox';
import { Label } from './components/ui/label';
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from './components/ui/card';
import { ScrollArea } from './components/ui/scroll-area';
import { Switch } from './components/ui/switch';
import { toast, Toaster } from './components/ui/use-toast';
import { getInstalledPackages, runPipCommand, getOperationLogs, PackageInfo, OperationLog } from './services/tauri-service';

const App: React.FC = () => {
  // 状态管理
  const [isSidebarOpen, setIsSidebarOpen] = useState(false);
  const [packages, setPackages] = useState<PackageInfo[]>([]);
  const [selectedPackages, setSelectedPackages] = useState<string[]>([]);
  const [isInstallDialogOpen, setIsInstallDialogOpen] = useState(false);
  const [installPackageName, setInstallPackageName] = useState('');
  const [installProgress, setInstallProgress] = useState(0);
  const [installOutput, setInstallOutput] = useState<string[]>([]);
  const [isInstalling, setIsInstalling] = useState(false);
  const [isDarkMode, setIsDarkMode] = useState(false);
  const [activeTab, setActiveTab] = useState('dashboard');
  const [logs, setLogs] = useState<OperationLog[]>([]);
  const [selectedPackage, setSelectedPackage] = useState<PackageInfo | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  // 切换深色模式
  useEffect(() => {
    if (isDarkMode) {
      document.documentElement.classList.add('dark');
    } else {
      document.documentElement.classList.remove('dark');
    }
  }, [isDarkMode]);

  // 初始化数据加载
  useEffect(() => {
    const loadData = async () => {
      try {
        setIsLoading(true);
        // 加载已安装的包列表
        const installedPackages = await getInstalledPackages();
        setPackages(installedPackages);
        
        // 加载操作日志
        const operationLogs = await getOperationLogs();
        setLogs(operationLogs);
      } catch (error) {
        console.error('加载数据失败:', error);
        toast({ title: '加载失败', description: '无法获取Python库信息，请检查Python环境' });
      } finally {
        setIsLoading(false);
      }
    };

    loadData();
  }, []);

  // 当切换到日志标签页时，刷新日志
  useEffect(() => {
    if (activeTab === 'logs') {
      refreshLogs();
    }
  }, [activeTab]);

  // 安装包
  const handleInstallPackage = async () => {
    if (!installPackageName.trim()) return;

    setIsInstalling(true);
    setInstallProgress(0);
    setInstallOutput([]);

    try {
      await runPipCommand('install', installPackageName, {
        onProgress: (line) => {
          setInstallOutput(prev => [...prev, line]);
          
          // 尝试从输出中提取进度信息
          const progressMatch = line.match(/(\d+)%/);
          if (progressMatch) {
            const progress = parseInt(progressMatch[1]);
            setInstallProgress(progress);
          } else if (line.includes('Downloading')) {
            // 如果没有明确的进度百分比，根据输出阶段更新进度
            const stageProgress = Math.min(95, Math.floor(installOutput.length / 2));
            setInstallProgress(stageProgress);
          }
        },
        onComplete: (success, output) => {
          if (success) {
            setInstallProgress(100);
            setTimeout(() => {
              // 安装成功后刷新包列表
              refreshPackages();
              setIsInstalling(false);
              setIsInstallDialogOpen(false);
              setInstallPackageName('');
              toast({ title: '安装成功', description: `已成功安装${installPackageName}` });
            }, 500);
          } else {
            setIsInstalling(false);
            toast({ 
              title: '安装失败', 
              description: '安装过程中出现错误',
              variant: 'destructive'
            });
          }
        }
      });
    } catch (error) {
      console.error('安装包失败:', error);
      setIsInstalling(false);
      toast({ 
        title: '安装失败', 
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      });
    }
  };

  // 卸载选中的包
  const handleUninstallPackages = async () => {
    if (selectedPackages.length === 0) return;

    setIsLoading(true);
    try {
      // 依次卸载每个选中的包
      for (const packageName of selectedPackages) {
        await runPipCommand('uninstall', packageName);
      }
      
      // 卸载完成后刷新包列表
      refreshPackages();
      setSelectedPackages([]);
      toast({ 
        title: '卸载成功', 
        description: `已成功卸载${selectedPackages.length}个包` 
      });
    } catch (error) {
      console.error('卸载包失败:', error);
      toast({ 
        title: '卸载失败', 
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      });
    } finally {
      setIsLoading(false);
    }
  };

  // 刷新包列表
  const refreshPackages = async () => {
    setIsLoading(true);
    try {
      const updatedPackages = await getInstalledPackages();
      setPackages(updatedPackages);
      toast({ title: '刷新成功', description: '包列表已更新' });
    } catch (error) {
      console.error('刷新包列表失败:', error);
      toast({ 
        title: '刷新失败', 
        description: '无法更新包列表',
        variant: 'destructive'
      });
    } finally {
      setIsLoading(false);
    }
  };

  // 刷新日志
  const refreshLogs = async () => {
    try {
      const updatedLogs = await getOperationLogs();
      setLogs(updatedLogs);
    } catch (error) {
      console.error('刷新日志失败:', error);
    }
  };

  // 更新单个包
  const handleUpdatePackage = async (packageName: string) => {
    setIsLoading(true);
    try {
      await runPipCommand('update', packageName);
      
      // 更新完成后刷新包列表
      refreshPackages();
      toast({ 
        title: '更新成功', 
        description: `已成功更新${packageName}` 
      });
    } catch (error) {
      console.error('更新包失败:', error);
      toast({ 
        title: '更新失败', 
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      });
    } finally {
      setIsLoading(false);
    }
  };

  // 卸载单个包
  const handleUninstallSinglePackage = async (packageName: string) => {
    setIsLoading(true);
    try {
      await runPipCommand('uninstall', packageName);
      
      // 卸载完成后刷新包列表
      refreshPackages();
      toast({ 
        title: '卸载成功', 
        description: `已成功卸载${packageName}` 
      });
    } catch (error) {
      console.error('卸载包失败:', error);
      toast({ 
        title: '卸载失败', 
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      });
    } finally {
      setIsLoading(false);
    }
  };

  // 处理包选择
  const handlePackageSelect = (packageName: string) => {
    setSelectedPackages(prev => 
      prev.includes(packageName)
        ? prev.filter(name => name !== packageName)
        : [...prev, packageName]
    );
  };

  return (
    <div className={`flex flex-col min-h-screen bg-background-${isDarkMode ? 'dark' : 'light'} text-primary transition-colors duration-300`}>
      {/* 顶部应用栏 */}
      <header className="sticky top-0 z-30 flex items-center justify-between h-16 px-4 bg-white dark:bg-slate-900 border-b border-border-light dark:border-border-dark shadow-sm">
        <div className="flex items-center gap-4">
          <Button variant="ghost" size="icon" onClick={() => setIsSidebarOpen(!isSidebarOpen)} className="md:hidden">
            <Menu className="h-5 w-5" />
          </Button>
          <h1 className="text-xl font-bold flex items-center gap-2">
            <Package className="h-6 w-6 text-primary" />
            PyLibrary Manager
          </h1>
        </div>
        
        <div className="flex items-center gap-2">
          <Button 
            onClick={() => setIsInstallDialogOpen(true)}
            className="gap-1 bg-primary text-white hover:bg-primary/90"
          >
            <Plus className="h-4 w-4" />
            安装
          </Button>
          <Button 
            onClick={handleRefreshPackages}
            variant="secondary"
            size="icon"
          >
            <RefreshCw className="h-4 w-4" />
          </Button>
          <div className="flex items-center gap-2">
            <Label htmlFor="dark-mode" className="sr-only">深色模式</Label>
            <Switch 
              id="dark-mode" 
              checked={isDarkMode} 
              onCheckedChange={setIsDarkMode} 
            />
          </div>
        </div>
      </header>

      <div className="flex flex-1 overflow-hidden">
        {/* 侧边导航 */}
        <aside 
          className={`
            fixed md:static inset-y-0 left-0 z-20 w-64 bg-white dark:bg-slate-900 border-r border-border-light dark:border-border-dark 
            transform transition-transform duration-300 ease-in-out
            ${isSidebarOpen ? 'translate-x-0' : '-translate-x-full md:translate-x-0'}
          `}
        >
          <div className="flex items-center justify-between p-4 md:hidden">
            <h2 className="font-bold">导航</h2>
            <Button variant="ghost" size="icon" onClick={() => setIsSidebarOpen(false)}>
              <X className="h-5 w-5" />
            </Button>
          </div>
          <nav className="p-4 space-y-1">
            <Button 
              variant={activeTab === 'dashboard' ? 'default' : 'ghost'} 
              className="w-full justify-start gap-2"
              onClick={() => setActiveTab('dashboard')}
            >
              <Package className="h-4 w-4" />
              库管理
            </Button>
            <Button 
              variant={activeTab === 'logs' ? 'default' : 'ghost'} 
              className="w-full justify-start gap-2"
              onClick={() => setActiveTab('logs')}
            >
              <Database className="h-4 w-4" />
              操作日志
            </Button>
          </nav>
        </aside>

        {/* 主内容区 */}
        <main className="flex-1 overflow-auto">
          {activeTab === 'dashboard' ? (
            <div className="p-4 md:p-6 max-w-7xl mx-auto">
              <div className="flex flex-col md:flex-row md:items-center justify-between gap-4 mb-6">
                <div>
                  <h2 className="text-2xl font-bold">已安装的Python库</h2>
                  <p className="text-secondary mt-1">管理当前Python环境中的第三方库</p>
                </div>
                <Button 
                  onClick={handleUninstallPackages}
                  disabled={selectedPackages.length === 0}
                  className="bg-destructive hover:bg-destructive/90 gap-1"
                >
                  <Trash2 className="h-4 w-4" />
                  批量卸载
                  <span className="ml-1 text-xs bg-white/20 rounded-full px-2 py-0.5">
                    {selectedPackages.length}
                  </span>
                </Button>
              </div>

              <Card>
                <CardContent className="p-0">
                  <ScrollArea className="h-[calc(100vh-240px)]">
                  {isLoading ? (
                    <div className="flex justify-center items-center h-64">
                      <div className="text-center">
                        <div className="animate-spin rounded-full h-8 w-8 border-4 border-slate-200 border-t-primary mx-auto mb-4"></div>
                        <p className="text-secondary">加载中...</p>
                      </div>
                    </div>
                  ) : packages.length === 0 ? (
                    <div className="flex justify-center items-center h-64">
                      <p className="text-secondary">未安装任何Python库</p>
                    </div>
                  ) : (
                    <Table>
                      <TableHeader>
                        <TableRow>
                          <TableHead className="w-[40px]"></TableHead>
                          <TableHead className="w-[200px]">库名称</TableHead>
                          <TableHead>版本</TableHead>
                          <TableHead className="hidden md:table-cell">描述</TableHead>
                          <TableHead className="text-right">操作</TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {packages.map((pkg) => (
                          <TableRow key={pkg.name}>
                            <TableCell>
                              <Checkbox 
                                id={pkg.name} 
                                checked={selectedPackages.includes(pkg.name)}
                                onCheckedChange={() => handlePackageSelect(pkg.name)}
                              />
                            </TableCell>
                            <TableCell className="font-medium">
                              <Button 
                                variant="link" 
                                className="p-0 h-auto text-primary hover:text-primary/80"
                                onClick={() => setSelectedPackage(pkg)}
                              >
                                {pkg.name}
                              </Button>
                            </TableCell>
                            <TableCell>{pkg.version}</TableCell>
                            <TableCell className="hidden md:table-cell text-secondary">
                              {pkg.summary || '无描述信息'}
                            </TableCell>
                            <TableCell className="text-right">
                              <Button 
                                variant="ghost" 
                                size="sm" 
                                className="text-secondary hover:text-primary"
                                onClick={() => handleUpdatePackage(pkg.name)}
                              >
                                更新
                              </Button>
                              <Button 
                                variant="ghost" 
                                size="sm" 
                                className="text-destructive hover:text-destructive/80"
                                onClick={() => handleUninstallSinglePackage(pkg.name)}
                              >
                                卸载
                              </Button>
                            </TableCell>
                          </TableRow>
                        ))}
                      </TableBody>
                    </Table>
                  )}
                </ScrollArea>
                </CardContent>
              </Card>

              {/* 包详情面板 */}
              {selectedPackage && (
                <Card className="mt-6 fade-in">
                  <CardHeader>
                    <div className="flex justify-between items-start">
                      <div>
                        <CardTitle>{selectedPackage.name}</CardTitle>
                        <CardDescription>版本: {selectedPackage.version}</CardDescription>
                      </div>
                      <Button 
                        variant="ghost" 
                        size="icon" 
                        onClick={() => setSelectedPackage(null)}
                      >
                        <X className="h-4 w-4" />
                      </Button>
                    </div>
                  </CardHeader>
                  <CardContent>
                    <div className="space-y-4">
                      <div>
                        <h4 className="text-sm font-medium text-secondary mb-1">描述</h4>
                        <p>{selectedPackage.summary || '无描述信息'}</p>
                      </div>
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                          <h4 className="text-sm font-medium text-secondary mb-1">安装位置</h4>
                          <p className="text-sm text-secondary">{selectedPackage.location || '未知'}</p>
                        </div>
                        <div>
                          <h4 className="text-sm font-medium text-secondary mb-1">依赖</h4>
                          <p className="text-sm text-secondary">暂无依赖信息</p>
                        </div>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              )}
            </div>
          ) : (
            <div className="p-4 md:p-6 max-w-7xl mx-auto">
              <h2 className="text-2xl font-bold mb-6">操作日志</h2>
              <Card>
                <CardContent className="p-0">
                  <ScrollArea className="h-[calc(100vh-240px)]">
                  {logs.length === 0 ? (
                    <div className="flex justify-center items-center h-64">
                      <p className="text-secondary">暂无操作日志</p>
                    </div>
                  ) : (
                    <Table>
                      <TableHeader>
                        <TableRow>
                          <TableHead>时间</TableHead>
                          <TableHead>操作类型</TableHead>
                          <TableHead>包名</TableHead>
                          <TableHead>状态</TableHead>
                          <TableHead className="hidden md:table-cell">命令</TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {logs.map((log) => (
                          <TableRow key={log.id}>
                            <TableCell className="text-sm text-secondary">{log.timestamp}</TableCell>
                            <TableCell>
                              <span className={`
                                px-2 py-1 rounded-full text-xs font-medium
                                ${log.operation_type === 'install' ? 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400'
                                : log.operation_type === 'update' ? 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400'
                                : 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400'}
                              `}>
                                {log.operation_type === 'install' ? '安装' : log.operation_type === 'update' ? '更新' : '卸载'}
                              </span>
                            </TableCell>
                            <TableCell className="font-medium">{log.package_spec}</TableCell>
                            <TableCell>
                              <div className="flex items-center gap-1">
                                {log.success ? (
                                  <CheckCircle className="h-4 w-4 text-success" />
                                ) : (
                                  <XCircle className="h-4 w-4 text-destructive" />
                                )}
                                <span>
                                  {log.success ? '成功' : '失败'}
                                </span>
                              </div>
                            </TableCell>
                            <TableCell className="hidden md:table-cell text-sm text-secondary truncate max-w-[200px]">
                              {log.command}
                            </TableCell>
                          </TableRow>
                        ))}
                      </TableBody>
                    </Table>
                  )}
                </ScrollArea>
                </CardContent>
              </Card>
            </div>
          )}
        </main>
      </div>

      {/* 安装包模态框 */}
      <Dialog open={isInstallDialogOpen} onOpenChange={setIsInstallDialogOpen}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle>安装新Python库</DialogTitle>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label htmlFor="package-name">库名称</Label>
              <Input 
                id="package-name"
                placeholder="例如: requests 或 pandas==2.0.3"
                value={installPackageName}
                onChange={(e) => setInstallPackageName(e.target.value)}
                disabled={isInstalling}
              />
              <p className="text-xs text-secondary">
                可以指定版本号，如: package_name==version
              </p>
            </div>
            
            {installProgress > 0 && (
              <div className="space-y-2">
                <div className="flex justify-between items-center">
                  <Label>安装进度</Label>
                  <span className="text-sm font-medium">{installProgress}%</span>
                </div>
                <Progress value={installProgress} className="h-2" />
              </div>
            )}
            
            {installOutput.length > 0 && (
              <ScrollArea className="h-32 border rounded-md p-3 bg-slate-50 dark:bg-slate-800 text-sm">
                {installOutput.map((line, index) => (
                  <div key={index} className="text-secondary dark:text-slate-300 whitespace-pre-wrap">
                    {line}
                  </div>
                ))}
              </ScrollArea>
            )}
          </div>
          <DialogFooter>
            <Button variant="ghost" onClick={() => setIsInstallDialogOpen(false)} disabled={isInstalling}>
              取消
            </Button>
            <Button 
              onClick={handleInstallPackage}
              disabled={!installPackageName.trim() || isInstalling}
              className="bg-primary hover:bg-primary/90"
            >
              {isInstalling ? '安装中...' : '开始安装'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 遮罩层（移动端侧边栏打开时） */}
      {isSidebarOpen && (
        <div 
          className="fixed inset-0 z-10 bg-black/50 md:hidden"
          onClick={() => setIsSidebarOpen(false)}
        ></div>
      )}

      {/* Toast通知 */}
      <Toaster />
    </div>
  );
};

export default App;
    </div>
  );
};

export default App;